#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
using piii = pair<int, pair<int, int>>;
#define P(i, j, k) piii(i, pii(j, k))
#define rep(i, a, b) for (int i = (a); i <= (b); i++)
#define per(i, a, b) for (int i = (a); i >= (b); i--)
#define endl '\n'
const int N = 1005;

int n, m;
char s[N][N];
int dis[3][N][N];
int xs, ys, xg, yg;
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};

int solve() {
  memset(dis, -1, sizeof(dis));
  dis[0][xs][ys] = 0;
  queue<piii> q;
  q.push(P(0, xs, ys));
  while (q.size()) {
    piii now = q.front();
    q.pop();
    int l = now.first;
    int x = now.second.first, y = now.second.second;
    rep(nl, 1, 2) {
      if (nl == l) continue;
      rep(i, 0, 3) {
        if (nl == 1 && dx[i] == 0) continue;  // nl == 1 along x
        if (nl == 2 && dx[i]) continue;       // nl == 2 along y
        int nx = x + dx[i], ny = y + dy[i];
        if (s[nx][ny] != '#' && s[nx][ny] != '\0' && dis[nl][nx][ny] == -1) {
          dis[nl][nx][ny] = dis[l][x][y] + 1;
          q.push(P(nl, nx, ny));
        }
      }
    }
  }
  int mn = 1e9;
  rep(i, 0, 2) if (dis[i][xg][yg] != -1) mn = min(mn, dis[i][xg][yg]);
  if (mn == 1e9) mn = -1;
  return mn;
}
int main() {
  ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  cin >> n >> m;
  rep(i, 1, n) rep(j, 1, m) cin >> s[i][j];
  rep(i, 1, n) rep(j, 1, m) {
    if (s[i][j] == 'S') xs = i, ys = j;
    if (s[i][j] == 'G') xg = i, yg = j;
  }
  cout << solve();
  return 0;
}